import pandas
import pandas as pd
from datetime import datetime, timedelta

from app_config import get_pro, get_engine_ts

pro = get_pro()
engine_ts = get_engine_ts()

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', None)


def fetch_data(start_date_str, end_date_str):
    df_q: pandas.DataFrame = pro.trade_cal(exchange='SSE', is_open='1',
                                           start_date=start_date_str,
                                           end_date=end_date_str,
                                           fields='cal_date')

    start_date = datetime.strptime(start_date_str, '%Y%m%d')
    end_date = datetime.strptime(end_date_str, '%Y%m%d')

    # 初始化一个空列表来存储日期
    dates = []

    # 使用循环生成日期范围内的所有日期
    current_date = start_date
    while current_date <= end_date:
        dates.append(current_date.strftime('%Y%m%d'))  # 将日期格式化为字符串
        current_date += timedelta(days=1)

    # 创建 DataFrame
    df = pd.DataFrame({'data': dates})

    df_sorted = df.sort_values(by='data', ascending=False).reset_index(drop=True)

    df_sorted = df_sorted.merge(df_q, how='left', left_on='data', right_on='cal_date')

    # 打印 DataFrame
    print(df_sorted)

    # df_q.rename(columns={'cal_date': 'date'}, inplace=True)
    # df_q.to_excel('aa.xlsx', sheet_name='sheet1', index=False)
    #
    perf_000016 = pd.read_excel("000016perf.xlsx", dtype={'日期Date': str})
    perf_000016 = perf_000016[['日期Date', '涨跌幅(%)Change(%)']].rename(columns={'涨跌幅(%)Change(%)': '上证50全'})

    print(perf_000016)
    # perf_000016 = perf_000016["", "", ""]
    # print(perf_000016)
    kk: pandas.DataFrame = df_sorted.merge(perf_000016, how='left', left_on='data', right_on='日期Date')
    print(kk)

    kk.to_excel("kk.xlsx")

    pass


if __name__ == '__main__':
    fetch_data('20250501', '20250616')
